package xyz.jangle.jdbc.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 插入数据库后，返回主键ID
 * @author Administrator
 *
 */
public class JdbcExample {
    public static void main(String[] args) {
    	// jdbc4已经不需要显式得加载驱动了
//    	try {
//			Class.forName("com.mysql.cj.jdbc.Driver");
////			Class.forName("com.mysql.jdbc.Driver");
//		} catch (ClassNotFoundException e1) {
//			e1.printStackTrace();
//		}
//        String url = "jdbc:mysql://127.0.0.1:3306/jangle_test?characterEncoding=UTF8&serverTimezone=UTC";
        String url = "jdbc:mysql://127.0.0.1:3306/jangle_test?characterEncoding=UTF8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "111111";
 
        String sql = "INSERT INTO demo (name, age) VALUES (?, ?)";
        
        try (Connection conn = DriverManager.getConnection(url, user, password);
        		//重点
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
             
            pstmt.setString(1, "value1");
            pstmt.setInt(2, 2);
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows == 0) {
                throw new SQLException("Creating user failed, no rows affected.");
            }
            
            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    long generatedId = generatedKeys.getLong(1); // 获取生成的ID
                    System.out.println("Generated ID: " + generatedId);
                } else {
                    throw new SQLException("Creating user failed, no ID obtained.");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
